function [stt,smooth_st,etamat,yfor]= gensys_sspace_sv( Y , SDX , modstr , fullp , into , instateloc, outpath , namestr)
% ===================================================================== 
% GENSYS_SSPACE_SV.m  
% 
% 
% Plot the actual series vs. 1step ahead forecasts 
%      Real-time and smoothed states for the whole system 
%      innovations and table with analysis of their properties   
%      when the mode has STOCHASTIC VOLATILITY 
% 
% Use GENSYS_SPPSACE for models without stochastic volatility 
% 
% function gensys_sspace( Y , modstr , fullp , into , outpath , namestr)
%
% Inputs 
% -------
% SDX       [T nx] matrix of stochastic volatilities 
% FULLP     Vector of paramaters ( including calibrated and volatilites which should be set to zero) 
% INTO      Structure with fields 
% OUTPATH   Path to store graph and tables ( do not call or leave empty ) 
% NAMESTR   String appended to all files created here 
% 
% INTO.SERNAMES     Series names for Columns of Y 
% INTO.STATENAMES   Names for the states, size NY  of G1 
% INTO.SHNAMES      Shock names for SDX 
% INTO.STARTEST     Start Date for Estimation 
% INTO.FINISHEST    Finishdate for Estimation 
% INTO.SAMPLE       Sample Vector 
% 
% Also use INTO to pass on all arguments to PLOTSAJ.M 
% 
% If OUTPATH and NAMESTR  provided, following files will be created 
% 
% Output 
% ======
% [YFORC namestr]      Plots of actual series vs. Forecasts 
% [INNOV namestr]      Plots of model innovations (SDX) 
% [ST namestr]         Plots of Real-time and smoothed states 
% [INNOV ANALYSIS namestr] Table with std, cross-correlations and VAR(1) 
%                           estimates for the innovations 
% 
% Alejandro Justiniano 11/2/2005  
% 
% Debugged using TEST_GENSYS_SSPACE_SV.M 
% ====================================================================
cucd = cd; 

[nobs,nn] = size(Y); 


[G1,CC,R,eu,junk,Z]=feval(modstr,fullp,[],[],[],1);
clear junk; 
nx = size(R,2); 

ch = size( SDX ); 
if ch(1) ~= nobs 
    error('Number of rows in SDX does not match Y Observations'); 
end 
if ch(2) ~= nx 
     error('Number of columns in SDX does not match Number of shocks'); 
end 
clear ch; 

if isequal( eu , [1;1] ) == 0
    error('Indeterminacy');
    return
end

if nargin < 7 | isempty( outpath ) == 1 ;
    flag_save = 0 ;
else
    if ~isempty( namestr );
        if isstr( char(namestr) ) == 0
            error('Must provide a string in NAMESTR')
        end
    else
        namestr = '';
    end
    flag_save = 1; 
end


% Check the settings for the initial state 
% =========================================
if isempty( instateloc ) == 1 
    disp('Initial state will not be used'); 
    flag_instate = 0 ;
else 
    instatloc = instateloc(:);  
    if length( instateloc ) ~= nn 
        error('Dimension Mistmatch: INSTATELOC and columns of Y'); 
    end 
    flag_instate = 1; 
    if max( instateloc ) > size(G1,1); 
        error('INSTATELOC entry exceeds dimension of state vector'); 
    end 
    
end 


[e,into]=ch_field( into, 'sernames' ); 
if e==0 
    into.sernames = fnumcell( 'Series ',[1:nn] ); 
end 

[e,into]=ch_field( into, 'shnames' ); 
if e==0 
    into.shnames = fnumcell( 'Shock ',[1:nx] ); 
end 
    
[e,into]=ch_field( into, 'stnames' ); 
temp = size( G1 , 1 ); 
if e==0 
    into.stnames = fnumcell( 'State ',[1:temp] );
end 


[e,into]=ch_field( into, 'sample' , ([1:nobs])' ); 
[e,into]=ch_field( into, 'startest' , 1 ); 
[e,into]=ch_field( into, 'finishest' , nobs ); 

tbeg = find( into.sample == into.startest ); 
tend = find( into.sample == into.finishest ); 

flag_cons = 0; 
if any( CC~=0 ) == 1 ;
    flag_cons = 1; 
    Cz = Z*CC;
    Cz = repmat( Cz' , [size(Y,1) 1] ); 
    Y = Y - Cz;
end

[stt,etamat,smooth_st,yfor,vstar,logLnc]=...
    kfilter_full(Y,Z,G1,R,SDX,flag_instate,instateloc);

% ===================================================================
% Truncate to the estimation sample or account for the initial state 
% ===================================================================
if tbeg == 1 & flag_instate == 1 
    tbeg = 2 ; 
end

if tbeg > 1; 
    
    stt     = stt(tbeg:tend,:); 
    etamat  = etamat(tbeg:tend,:); 
    yfor    = yfor(tbeg:tend,:); 
    smooth_st = smooth_st(tbeg:tend,:); 
   
    % Add the constants if there are any 

end 

if flag_cons == 1
    Y = Y + Cz;
    newt = size(stt,1);
    Cmat = repmat( CC' , [newt 1]);
    stt  = stt + Cmat ;
    smooth_st = smooth_st + Cmat;
    yfor = yfor + Cz(1:newt,:);
end

samp   = into.sample( tbeg:tend );

nobs = size( yfor ,1 ); 
Y    = Y(tbeg:tend,:); 

if size(Y,1) ~= nobs 
    error('Dimension Mistmach Y and Forecast') 
end 

% =================================================
%        Create output cells 
% ==================================================
samp_cell = num2cprec( samp , 2 ); 

temp_top = combine_cells( [] , ' ' , into.stnames , ' Stt ' )'; 
ocell   = crtcell( stt , samp_cell , temp_top , 'Stt States' , 1 ); 

temp_top = combine_cells( [] , ' ' , into.stnames , ' St Smooth ' )'; 
st_cell = crtcell( smooth_st , samp_cell  , temp_top , 'Smooth State' , 1 ); 
ocell   = merge_cells( ocell, st_cell , 2 ); 

if flag_save == 1 
savecell( ocell , cucd, outpath , 'States'); 
end 
clear ocell; 

temp_top = combine_cells( [] , ' ' , into.shnames , ' innov' ); 
ocell = crtcell( etamat , samp_cell , temp_top , 'Disturbance Innovation'); 
if flag_save == 1 
    savecell( ocell , cucd , outpath , 'Innovations' ); 
end 


% =================================================
% Plot the actual series relative to the forecasts 
% =================================================
if flag_save == 1 
    into.opath = outpath; 
    into.gname = ['YFORC ',namestr]; 
end 

if nn > 6; 
    into.m = 2; 
    into.n = 3; 
    into.titfont = 7; 
end 

into.title = ' ,Actual & 1-SAF'; 
into.legend = {'Actual ';'1-SAF '}; 
into.cnames = into.legend;  
into.pnames = into.sernames; 
into.xaxis  = into.sample(tbeg:tend) ; 

xmat = zeros( nobs, 2, nn); 
xmat(:,1 ,: ) = Y ; 
xmat(:,2 , : ) = yfor ; 

plotsaj( xmat , 1 , into ); 
clear xmat ; 

% =================================================
% Plot the actual series relative to the forecasts 
% =================================================
if flag_save == 1 
    into.gname = ['INNOV ',namestr]; 
end 

if size( SDX,1 ) > 6 
    into.m = 2; 
    into.n = 3; 
elseif nn > 6 
    into =  rmfield( into , 'm'); 
    into =  rmfield( into , 'n');
end 
    
into.title = ' ,INOV '; 
into =  rmfield( into , 'legend'); 
into =  rmfield( into , 'pnames '); 
into.cnames = into.shnames ; 

plotsaj( etamat , 2, into ); 

% =================================================
% Plot the actual series relative to the forecasts 
% =================================================
temp = size( G1 ,1 ); 
if temp > 8 
    into.m = 2; 
    into.n = 4; 
end

% =================================================
% Plot the actual vs. Smoothed States 
% =================================================
into.pnames = into.stnames ; 
if flag_save == 1 
    into.gname = ['ST ',namestr]; 
end 
    
xmat = zeros( nobs , 2 , temp ); 
xmat(:,1,:) = stt; 
xmat(:,2,:) = smooth_st;

into.legend = {'Stt ','Smooth'}; 
into.cnames = into.legend; 
into.title = '';
into.width=[1.3 1]; 
plotsaj( xmat , 1 , into ); 

clear xmat temp; 

% ===============================
%  Analysis of the innovations 
% ===============================
emat_cor  = corrcoef( etamat ); 
emat_std  = std( etamat ); 
[emat_var ,emat_res]  = ols( etamat(2:end,:) , etamat(1:end-1,:) );

emat_cell = emptycell( 4 , nx +1 ); 
emat_cell(1,1:2) ={'SAMPLED','INNOVATIONS'}; 

emat_cell(3,1) = {'STD INNOVATIONS'}; 
emat_cell(3,2:end) = ( into.shnames(:) )'; 
emat_cell(4,2:end) = num2cprec( emat_std ); 

emat_c2 = crtcell( emat_cor , into.shnames , into.shnames , 'CORR INNOV' , 1); 
emat_cell = merge_cells( emat_cell , emat_c2 , 1 ); 
clear emat_c2; 

emat_c3 = crtcell( emat_var , into.shnames , into.shnames , 'VAR1 INNOV' , 1 ); 
emat_cell = merge_cells( emat_cell , emat_c3 , 1 ); 
clear emat_c3; 

printcell( emat_cell ); 
if flag_save == 1 ; 
    savecell( emat_cell, cucd, outpath , ['INNOV ANALYSIS ',namestr] ); 
end 
